package messageMeServer.utility;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import messageMeUtility.user.StandardUser;
import messageMeUtility.interfaces.IUser;

public class UserDataReader {

	public UserDataReader() {
	}
	
	public List<IUser> read() {
	
		List<IUser> result = new ArrayList<IUser>();

		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder;

			docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(new File(".\\data\\Users.xml"));
			doc.getDocumentElement().normalize();

			Element usersElement = doc.getDocumentElement();

			NodeList users = usersElement.getElementsByTagName("User");

			for (int index = 0; index < users.getLength(); index++) {
				Node user = users.item(index);
				result.add(this.getUser(user));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private IUser getUser(Node userNode) {
		Element user = (Element) userNode;

		return new StandardUser(user.getAttribute("name"),
				user.getAttribute("email"), user.getAttribute("password"));
	}
}
